import { BubbleMenuPlugin  } from '@tiptap/extension-bubble-menu'
import {
  defineComponent,
  h,
  onBeforeUnmount,
  onMounted, 
  ref,
} from 'vue'
import Eventbus from '../../urtls/eventBus';
export const BubbleMenu = defineComponent({
  name: 'BubbleMenu',

  props: {
    pluginKey: {
      // TODO: TypeScript breaks :(
      // type: [String, Object as PropType<Exclude<BubbleMenuPluginProps['pluginKey'], string>>],
      type: null,
      default: 'bubbleMenu',
    },

    editor: {
      type: Object ,
      required: true,
    },

    tippyOptions: {
      type: Object,
      default: () => ({}),
    },

    shouldShow: {
      type: Boolean,
      default: null,
    },
  },

  setup(props, { slots }) {
    const root = ref<HTMLElement | null>(null)

    onMounted(() => { 
      const {
        pluginKey,
        editor,
        tippyOptions,
        shouldShow,
      } = props
      //修复源码问题
      Eventbus.on('onCreateBubbleMenu',(e)=>{
        e.registerPlugin(BubbleMenuPlugin({
            pluginKey,
            editor:e,
            element: root.value as HTMLElement,
            tippyOptions,
            shouldShow,
          }))
      }) 
    })

    onBeforeUnmount(() => {
      const { pluginKey, editor } = props
      
      editor.unregisterPlugin(pluginKey)
    })

    return () => h('div', { ref: root }, slots.default?.())
  },
})
